package org.geektime.task.automybatis.config;


import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 通过实现ApplicationContextAware接口获得上下文信息，从而获得动态注册的SqlSessionFactoryBean对象
 */
public class MyBatisAnnotionDriverSupport implements ApplicationContextAware {

    private ApplicationContext applicationContext;
    private SqlSessionFactory sqlSessionFactory;

    public SqlSession getSession(){
        return sqlSessionFactory.openSession();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        System.out.println("初始化获得Sprig上下文对象");
    }

    @PostConstruct
    public void init(){
        SqlSessionFactoryBean sqlSessionFactoryBean = applicationContext.getBean(SqlSessionFactoryBean.class);
        try {
            this.sqlSessionFactory = sqlSessionFactoryBean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("加载sqlSessionFactory结束");
    }


}
